<?php

namespace app\admin\service;

use app\admin\service\RuleService;
use app\model\Admin;
use app\common\Error;
use think\facade\Db;
use think\facade\Session;

use think\facade\Cache;

/**
 * 登录注册服务类
 */
class LoginService
{
    private $adminModel;

    public function __construct(Admin $adminModel)
    {
        $this->adminModel = $adminModel;
    }

    /**
     * 用户后台登录
     *
     * @dateTime 2022/09/06
     * @param string username
     * @param string password
     * @return array
     * @author zhixiang0215@126.com
     */
    public function userLogin($params)
    {
        $username = addslashes(strip_tags($params['username']));
        $password = addslashes(strip_tags($params['password']));

        $data = $this->adminModel->getInfoByWhere(['name' => $username], 'id, rule_id, name, nickname, password');

        if (empty($data)) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::USER_NOT_EXIXTS];
        }

        if (!password_verify($password, $data['password'])) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::PASSWORD_ERROR];
        }

        Session::set('user_id', $data['id']);
        Session::set('rule_id', $data['rule_id']);
        Session::set('user_name', $data['nickname']);

        $auth = (new RuleService)->getRuleDetail($data['rule_id']);
        $whereauth = [];
        if (Session::get('rule_id') == 1 || Session::get('rule_id') == 2) {

        } else {
            $whereauth[] = ['id', 'in', $auth['menu_ids']];
        }
        $allauth = Db::name('admin_menu')->where($whereauth)->column('path');

        Session::set('allauth', $allauth);
//        var_dump(  in_array('/admin/type/index',Session::get('allauth')));
//        var_dump($allauth);
//        exit();

        $menu = (new RuleService)->getMenuData();

        if (empty($menu)) {
            return ['code' => Error::LOGIN_ERROR_CODE, 'message' => Error::LOGIN_ERROR];
        }

        return [];
    }

    /**
     * 用户后台注册
     *
     * @dateTime 2022/09/06
     * @param string username
     * @param string password
     * @return array
     * @author zhixiang0215@126.com
     */
    public function userRegister($params)
    {
        $username = addslashes(strip_tags($params['username']));
        $password = addslashes(strip_tags($params['password']));

        $data = $this->adminModel->getInfoByWhere(['name' => $username], 'id');

        if ($data) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::USERNAME_EXISTS];
        }

        $createData = [
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'name' => $username,
            'created_at' => now()
        ];
        $id = $this->adminModel->edit($createData);

        if (!$id) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::PLEASE_CONTACT_THE_DEVELOPER];
        }
        return [];
    }
}